
//删除用户逻辑处理，传入用户id
function delUser(id) {
    if (id == userId) {
        alert("不可删除当前用户！");
        return;
    }
    confirm("确定删除此用户吗？<br/>与此用户关联的子系统用户将无法使用子系统！", function (result) {
        if (result) {
            $.ajax({
                url: "deleteUser",
                type: "post",
                data: {"userId": id},
                dataType: "json",
                success: function (data) {
                    let status = data.status
                    if(status == 0){
                        alert("删除成功！", ctx + "/toUserMaintain");
                    }else{
                        alert("删除失败，请稍后重试！");
                    }
                },
                error: function () {
                    alert("删除失败，请稍后重试！");
                }
            })
        }
    });
}

//增加用户
function save() {
    cancleAction();
    $.ajax({
        url: "getDeptAndRoles",
        type: "post",
        dataType: "json",
        success: function (data) {
            let status = data.status
            if(status == 0){
                let roles = data.roles;
                for (let i = 0; i < roles.length; i++) {
                    let checkBox = '<li style="list-style-type: none"><input type="checkbox" onclick="cancelOtherChecked(this,&quot;role&quot;);" name="role" value="' + roles[i].roleId + '"><span>' + roles[i].roleName + '</span></li>';
                    $("#roles").append(checkBox);
                }
                let setting2 = {
                    data: {
                        simpleData: {
                            enable: true
                        }
                    },
                    callback: {
                        onClick: onClick
                    },
                    view: {
                        showIcon: false
                    }
                };
                $.fn.zTree.init($("#treeDemo"), setting2, data.orgs);
            }else{
                alert("获取失败！");
            }
        },
        error: function () {
            alert("系统忙，请稍后重试！");
        }
    })
}

//点击当前权限将其他权限取消选中
function cancelOtherChecked(obj, name) {
    //记录下现在是否被选中
    let flag = $(obj).is(':checked');
    //将所有的选中状态都取消
    $("input[name='" + name + "']").each(function () {
        $(this).prop("checked", false);
        $(this).parent().removeClass("checked");
    })
    //如果现在是选中状态，说明之前是没选中的，加上checked
    if (flag) {
        $(obj).prop("checked", true);
        $(obj).parent().addClass("checked");

    } else {   //如果现在不是选中状态，说明之前是选中的，去除checked
        $(obj).prop("checked", false);
        $(obj).parent().removeClass("checked");
    }

}

//组织节点点击回调函数
function onClick(event, treeId, treeNode) {
    let nodeId = treeNode.id;
    $("#orgId").val(nodeId);
}

//增加用户逻辑处理
function saveUser() {
    let key = genAesSecret()
    let username = $("#username").val().trim();
    let password = $("#password").val().trim();
    let compelltion = $("#compelltion").val().trim();
    let surePasseword = $("#surePassword").val().trim();
    if (username == "") {
        alert("用户名不能为空！");
        return;
    }
    username = encrypt(username,key)
    if (compelltion == "") {
        alert("请填写姓名！");
        return;
    }
    if (password == "") {
        alert("请输入密码！");
        return;
    }
    if(!regex.test(password)){
        alert("密码强度不符合要求（须包含大小写字母、数字及特殊字符，且长度8位以上）！")
        return;
    }
    if (surePasseword == "") {
        alert("请输入确认密码！");
        return;
    }
    if (surePasseword != password) {
        alert("两次输入密码不一致！");
        return;
    }
    password = encrypt(password,key)
    let orgid = $("#orgId").val();
    if (orgid == "") {
        alert("请选择一个部门！");
        return;
    }
    let role = $("input[name='role']:checked").val();

    let roleName = $("input:checkbox[name='role']:checked").next().text();
    //console.log(roleName)
    if (isShowAll == '1') {
        if (roleName == "总调") {
            alert("你没有权限指定一个人为总调！");
            return;
        }
    }
    if (isShowAll == '2') {
        if (roleName != null || roleName != "") {
            alert("你没有分配权限！");
            return;
        }
    }
    $.ajax({
        url: "saveUser",
        type: "post",
        data: {"username": username, "password": password, "orgid": orgid, "compelltion": compelltion, "roleId": role,"key":key},
        dataType: "json",
        success: function (data) {
            let status = data.status
            if(status == 0){
                alert(data.msg, ctx + "/toUserMaintain");
            }else{
                alert("添加用户失败！")
            }
        },
        error: function () {
            alert("系统忙，请稍后重试！");
        }
    })

}

//取消增加/修改用户
function cancleAction() {
    $("#username").val("");
    $("#password").val("");
    $('select[name="deptid"]').empty();
    $("#NowUserName").val("");
    $("#NowDept").val("");
    $('select[name="moveDeptId"]').empty();
    $("#alter").hide();
    $("#save").hide();
    $("#roles").children().remove();
    $("#orgId").val("");
    $("#roles1").children().remove();
    $("#orgId1").val("");
    $("#compelltion").val("");
    $("#surePassword").val("");
}

//修改用户
function alterUser(userId) {
    cancleAction();
    $.ajax({
        url: "getUserInfo",
        type: "post",
        data: {"userId": userId},
        dataType: "json",
        success: function (data) {
            let status = data.status
            if(status == 0){
                let user = data.user;
                let username = user.username;
                let deptname = user.organization.deptname;
                let authRole = data.authRole;
                let compelltion = user.compelltion;
                $("#NowUserName").val(username);
                $("#NowDept").val(deptname);
                $("#userId").val(userId);
                $("#Nowcompelltion").val(compelltion);
                let roles = data.roles;
                for (let i = 0; i < roles.length; i++) {
                    let checkBox = '<li style="list-style-type: none"><input type="checkbox" onclick="cancelOtherChecked(this,&quot;role1&quot;);" name="role1" value="' + roles[i].roleId + '">' + roles[i].roleName + '</li>';
                    $("#roles1").append(checkBox);
                }
                if (authRole != null) {
                    let roleId = authRole.roleId;
                    $("input[value='" + roleId + "']").attr("checked", "checked");
                }
                let setting2 = {
                    data: {
                        simpleData: {
                            enable: true
                        }
                    },
                    callback: {
                        onClick: onClick1
                    },
                    view: {
                        showIcon: false
                    }
                };
                $.fn.zTree.init($("#treeDemo1"), setting2, data.orgs);
            }else{
                alert("获取失败！")
            }
        },
        error: function () {
            alert("系统忙，请稍后重试！");
        }
    })
}

function onClick1(event, treeId, treeNode) {
    let nodeId = treeNode.id;
    $("#orgId1").val(nodeId);
}

//修改用户逻辑处理
function moveUser() {
    let userId = $("#userId").val();
    let orgid = $("#orgId1").val();
    let compelltion = $("#Nowcompelltion").val().trim();
    let role = $("input[name='role1']:checked").val();
    let roleName = $("input:checkbox[name='role1']:checked").next().text();
    if (compelltion == "") {
        alert("请填写姓名！");
        return;
    }
    if (isShowAll == '1') {
        if (roleName == "总调") {
            alert("你没有权限指定一个人为总调！");
            return;
        }
    }
    if (isShowAll == '2') {
        if (roleName != null || roleName != "") {
            alert("你没有分配权限！");
            return;
        }
    }
    $.ajax({
        url: "alterUser",
        type: "post",
        data: {"userId": userId, "orgid": orgid, "roleId": role, "compelltion": compelltion},
        dataType: "json",
        success: function (data) {
            let status = data.status
            if(status == 0){
                alert(data.msg, ctx + "/toUserMaintain");
            }else{
                alert("修改失败！")
            }
        },
        error: function () {
            alert("系统忙，请稍后重试！");
        }
    })
}

/**
 * 重置用户登录密码
 */
function forceResetPassword(id) {
    if (id == userId) {
        alert("不可重置当前用户的登录密码！");
        return;
    }
    confirm("确定要重置此用户的登录密码吗？", function (result) {
        if (result) {
            $.ajax({
                url: "forceResetPassword",
                type: "post",
                data: {"userId": id},
                dataType: "json",
                success: function (data) {
                    let status = data.status
                    if(status == 0){
                        alert("重置登录密码成功！")
                    }else{
                        alert("重置登录密码失败！")
                    }
                },
                error: function () {
                    alert("系统忙，请稍后重试！");
                }
            })
        }
    });
}


